#!/usr/bin/env python

import iutil
import os
import subprocess
import re
import sys, stat
import gettext

_ = lambda x: gettext.ldgettext("isoft_svmc", x)

noroot_nodev_flag = True
tmp_mount_flag = True 
shm_mount_flag = True 
gettext.gettext("off")

rootPath = "/mnt/sysimage"
livePath = "/mnt/live"

conf_pattern = {"mount_noroot":("/etc/fstab", [".+/\w+.+ext[234].+nodev.+\s*"]),
		"mount_tmp":("/etc/fstab", [".+/tmp.+((nodev|nosuid|noexec)[,]?){3}.+\s*"]),
		"mount_shm":("/etc/fstab", [".+/dev/shm.+((nodev|nosuid|noexec)[,]?){3}.+\s*"]),
		"usb_storage":("/etc/modprobe.d/modprobe.conf", ["\s*install\s+usb-storage\s+/bin/true\s*"]),
		"ipv6_mod":("/etc/modprobe.d/modprobe.conf", ["\s*install\s+ipv6\s+/bin/true\s*"]),
		"uncommon_protocol":("/etc/modprobe.d/modprobe.conf",
				["\s*install\s+dccp\s+/bin/true\s*",
				 "\s*install\s+sctp\s+/bin/true\s*",
				 "\s*install\s+rds\s+/bin/true\s*",
				 "\s*install\s+tipc\s+/bin/true\s*"
				]),
		"usb_device":("/boot/grub/grub.conf", [".*kernel.+nousb.*\s*"]),
		"daemon_umask":("/etc/sysconfig/init", [".*umask\s+027\s*"]),
		"core_dump_1":("/etc/security/limits.conf", [".*[*]\s+hard\s+core\s+0\s*"]),
		"core_dump_2":("/etc/security/sysctl.conf", [".*fs\.suid_dumpable\s*=\s*0\s*"]),
		"prelink":("/etc/sysconfig/prelink", [".*PRELINKING\s*=\s*no\s*"]),
		"ip_traffic":("/etc/sysctl.conf", 
				[".*net\.ipv4\.conf\.all\.send_redirects\s*=\s*0\s*",
				 ".*net\.ipv4\.conf\.default\.send_redirects\s*=\s*0\s*"
				]),
		"ipv6_ifcfg":("/etc/sysconfig/network-scripts/ifcfg-eth0", [".*IPV6INIT\s*=\s*no\s*"]),
		"password":("/etc/pam.d/system-auth-ac", [".*password\s+requisite\s+pam_passwdqc\.so\s+min\s*=\s*disabled,8,8,8,8\s*"]),
		"single_user":("/etc/init/rcS-sulogin.conf", [".*exec\s+/sbin/sulogin\s*"]),
		"tmout":("/etc/profile.d/tmout.sh", [".*TMOUT\s*=\s*900\s*"]),
		"root_graphical":("/etc/pam.d/gdm-password", [".*auth\s+required\s+pam_succeed_if\.so\s+user\s*!=\s*root\s+quiet\s*"]),
		"modulesig":("/boot/grub/grub.conf", [".*enforcemodulesig\s*=\s*1.*\s*"]),
		"fail_lock":("/etc/pam.d/system-auth-ac", 
		[".*auth\s+required\s+pam_tally2\.so\s+deny\s*=\s*5\s+onerr\s*=\s*fail\s+unlock_time\s*=\s*900\s*",
		 ".*account\s+required\s+pam_tally2\.so\s*" ]) 
		}

ret_msg = {0:"OK", 1:"File not found", 2:"Dependence not meet", 3:"Permisson denied"}



def mount_for_noroot():
	global noroot_nodev_flag
	noroot_nodev_flag = True 
	return 


def mount_for_tmp():
	global tmp_mount_flag
	tmp_mount_flag = True 
	return 


def mount_for_shm():
	global shm_mount_flag
	shm_mount_flag = True 
	return 

def no_mount_for_noroot():
	global noroot_nodev_flag
	noroot_nodev_flag = False 
	return 


def no_mount_for_tmp():
	global tmp_mount_flag
	tmp_mount_flag = False 
	return 


def no_mount_for_shm():
	global shm_mount_flag
	shm_mount_flag = False 
	return 

					
def replace_conf(old, new, keep="no"):
	if os.path.exists(old):
		perm = os.stat(old)[0] & 0777
	else:
		perm = 0644
	proc = subprocess.Popen("install -m %o %s %s"% (perm, new, old), shell=True)
	proc.wait()

	if keep == "no":
		proc = subprocess.Popen("rm -f %s"% new, shell=True)
		proc.wait()
	
	# label it 
	proc = subprocess.Popen("restorecon %s"% old, shell=True)
	proc.wait()
	return 0

def repair_perm(file):
	os.chmod(file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)

	# label it 
	proc = subprocess.Popen("restorecon %s"% file, shell=True)
	proc.wait()
	return 0


def add_nodev_for_fstab():

	fstab = rootPath + '/etc/fstab' 
	e = os.path.exists(fstab) 
	if False==e:
		return 1

	fstab_old = file(fstab, 'r') 
	fstab_new = file(fstab + '_tmp', 'w') 

	tmp_flag = True
	for line in fstab_old.readlines():

		line = line.strip() 
		if not len(line) or line.startswith('#'): 
			fstab_new.write(line+'\n') 
			continue 

		array = line.split() 

		if array[1]=='/': # directory'/' no need to change
			fstab_new.write(line+'\n') 
			continue 

		# no '/' directorys which the type is ext3/ext4/ext2, should add 'nodev' option
		if ('ext3'==array[2] or 'ext4'==array[2] or 'ext2'==array[2]) and True==noroot_nodev_flag: 
			if 'defaults'==array[3]:
				array[3] = 'nodev' 
			else:
				if -1==array[3].find('nodev'): # no 'nodev' option, add it
					array[3] = array[3] + ',nodev'

		# directory '/dev/shm' need to add 'nodev','nosuid','noexec'
		if '/dev/shm'==array[1] and True==shm_mount_flag: 

                        if 'defaults'==array[3]:
                                array[3] = 'nodev' 
                        else:
                                if -1==array[3].find('nodev'):
                                        array[3] = array[3] + ',nodev' 

                        if -1==array[3].find('nosuid'):
                                array[3] = array[3] + ',nosuid' 

                        if -1==array[3].find('noexec'):
                                array[3] = array[3] + ',noexec' 

		# directory '/tmp' need to add 'nodev','nosuid','noexec'
		if '/tmp'==array[1] and True==tmp_mount_flag: 
			tmp_flag = False

                        if 'defaults'==array[3]:
                                array[3] = 'nodev' 
                        else:
                                if -1==array[3].find('nodev'):
                                        array[3] = array[3] + ',nodev' 

                        if -1==array[3].find('nosuid'):
                                array[3] = array[3] + ',nosuid' 


		for str in array:
                        fstab_new.write(str+'\t') 
		fstab_new.write('\n') 

	#if tmp_flag == True:
	#tmp_noexec()
		

	fstab_new.close() 
	fstab_old.close() 

	replace_conf(fstab, fstab+ "_tmp")

	return 0

def del_nodev_for_fstab():

	fstab = rootPath + '/etc/fstab' 
	e = os.path.exists(fstab) 
	if False==e:
		return  1

	fstab_old = file(fstab, 'r') 
	fstab_new = file(fstab + '_tmp', 'w') 

	for line in fstab_old.readlines():

		line = line.strip() 
		if not len(line) or line.startswith('#'): 
			fstab_new.write(line+'\n') 
			continue 

		array = line.split() 

		if array[1]=='/': # directory'/' no need to change
			fstab_new.write(line+'\n') 
			continue 

		# no '/' directorys which the type is ext3/ext4/ext2, should add 'nodev' option
		if ('ext3'==array[2] or 'ext4'==array[2] or 'ext2'==array[2]) and noroot_nodev_flag == False:
                        if -1 != array[3].find('nodev'): # no 'nodev' option, add it
                                array[3] = re.sub("nodev[,]?", "", array[3])
			if array[3] == "":
				array[3] = "defaults"

		# directory '/dev/shm' need to add 'nodev','nosuid','noexec'
		if '/dev/shm'==array[1] and shm_mount_flag == False: 

                        if -1 != array[3].find('nodev'):
                                array[3] = re.sub("nodev[,]?", "", array[3])

                        if -1 != array[3].find('nosuid'):
                                array[3] = re.sub("nosuid[,]?", "", array[3])

                        if -1 != array[3].find('noexec'):
                                array[3] = re.sub("noexec[,]?", "", array[3])

			if array[3] == "":
				array[3] = "defaults"

		# directory '/tmp' need to add 'nodev','nosuid','noexec'
		if '/tmp'==array[1] and tmp_mount_flag == False:
                        if -1 != array[3].find('nodev'):
                                array[3] = re.sub("nodev[,]?", "", array[3])

                        if -1 != array[3].find('nosuid'):
                                array[3] = re.sub("nosuid[,]?", "", array[3])

			if array[3] == "":
				array[3] = "defaults"
		for str in array:
                        fstab_new.write(str+'\t') 
                fstab_new.write('\n') 

	fstab_new.close() 
        fstab_old.close() 

	replace_conf(fstab, fstab + "_tmp")
	return 0


def disable_usb_storage():
	modprobe_path = rootPath + '/etc/modprobe.d/modprobe.conf' 
        if True==os.path.exists(modprobe_path): # '/etc/modprobe.d/modprobe.conf' is exist
	        old_conf = file(modprobe_path, 'r') 
                new_conf = file(modprobe_path+'_tmp', 'w') 

                for line in old_conf.readlines():
                        line = line.strip() 
                        if not len(line) or line.startswith('#'):
                                new_conf.write(line+'\n') 
                                continue 

                        if -1!=line.find('usb-storage'): # find 'usb-storage', just skip this line
                                continue 

                        #if -1!=line.find('ipv6'):
                        #        new_conf.write('install ipv6 /bin/true\n') 
                        #        continue 

                        new_conf.write(line+'\n') 

                new_conf.write('install usb-storage /bin/true\n') 

                old_conf.close() 
		new_conf.close() 

		replace_conf(modprobe_path, modprobe_path + '_tmp')
                return 0

        conf = file(modprobe_path, 'w')  # create new file '/etc/modprobe.d/modprobe.conf'
        conf.write('install usb-storage /bin/true\n') 
        conf.close() 
	repair_perm(modprobe_path)
	return 0

def enable_usb_storage():
	modprobe_path = rootPath + '/etc/modprobe.d/modprobe.conf' 
        if True==os.path.exists(modprobe_path): # '/etc/modprobe.d/modprobe.conf' is exist
                old_conf = file(modprobe_path, 'r') 
                new_conf = file(modprobe_path+'_tmp', 'w') 
		pattern = re.compile(conf_pattern["usb_storage"][1][0])

                for line in old_conf.readlines():
                        line = line.strip() 

			if pattern.match(line):
				continue

                        new_conf.write(line+'\n') 


                old_conf.close() 
		new_conf.close() 

		replace_conf(modprobe_path, modprobe_path + '_tmp')
		return 0
	return 1


def disable_usb_device():
        grub_path = rootPath + '/boot/grub/grub.conf' 
        if True!=os.path.exists(grub_path):
                return 1

        old_grub = file(grub_path, 'r') 
        new_grub = file(grub_path+'_tmp', 'w') 

        for line in old_grub.readlines():

                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        new_grub.write(line+'\n') 
                        continue 

                if -1!=line.find('kernel') and -1!=line.find('vmlinuz'):
                        if -1==line.find('nousb'): # not found 'nousb' in kernel command
                                new_grub.write(line+' nousb\n') 
                                continue 

                new_grub.write(line+'\n') 

        old_grub.close() 
        new_grub.close() 
	replace_conf(grub_path, grub_path + '_tmp')
	return 0

def enable_usb_device():
        grub_path = rootPath + '/boot/grub/grub.conf' 
        if True!=os.path.exists(grub_path):
                return 1

	pattern = re.compile(conf_pattern["usb_device"][1][0])
        old_grub = file(grub_path, 'r') 
        new_grub = file(grub_path+'_tmp', 'w') 

        for line in old_grub.readlines():

                line = line.strip() 

		if pattern.match(line):
			line = line.replace('nousb' ,'')

                new_grub.write(line+'\n') 

        old_grub.close() 
        new_grub.close() 

	replace_conf(grub_path, grub_path + '_tmp')

        return 0



def daemon_umask():
	init_path = rootPath + '/etc/sysconfig/init' 
        if True!=os.path.exists(init_path):
                return 1

        init_old = file(init_path, 'r') 
        init_new = file(init_path+'_tmp', 'w') 

        for line in init_old.readlines():
                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        init_new.write(line+'\n') 
                        continue 

                if -1!=line.find('umask'): # find 'umask', and skip this line
                        continue 

                init_new.write(line+'\n') 

        init_new.write('umask 027\n') 

        init_old.close() 
        init_new.close() 

	replace_conf(init_path, init_path + '_tmp')
	return 0

def no_daemon_umask():
	init_path = rootPath + '/etc/sysconfig/init' 
        if True!=os.path.exists(init_path):
                return 1

        init_old = file(init_path, 'r') 
        init_new = file(init_path+'_tmp', 'w') 
	pattern = re.compile(conf_pattern["daemon_umask"][1][0])

        for line in init_old.readlines():
                line = line.strip() 

                if pattern.match(line):
                        continue 

                init_new.write(line+'\n') 

        init_old.close() 
        init_new.close() 

	replace_conf(init_path, init_path + '_tmp')

	return 0


def disable_core_dump():
	limits_path = rootPath + '/etc/security/limits.conf' 
        if True!=os.path.exists(limits_path):
                return 1

        limits_old = file(limits_path, 'r') 
        limits_new = file(limits_path+'_tmp', 'w') 

        for line in limits_old.readlines():
                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        limits_new.write(line+'\n') 
                        continue 

                if -1!=line.find('core'): # find 'core', and skip this line
                        continue 

                limits_new.write(line+'\n') 

        limits_new.write('*\thard\tcore\t0\n') 

        limits_old.close() 
        limits_new.close() 

	replace_conf(limits_path, limits_path + '_tmp')


        sysctl_path = rootPath + '/etc/sysctl.conf' 
        if True!=os.path.exists(sysctl_path):
                return 1

        sysctl_old = file(sysctl_path, 'r') 
        sysctl_new = file(sysctl_path+'_tmp', 'w') 

        for line in sysctl_old.readlines():
                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        sysctl_new.write(line+'\n') 
                        continue 

                if -1!=line.find('fs.suid_dumpable'): # find 'fs.suid_dumpable', just skip this line
                        continue 

                sysctl_new.write(line+'\n') 

        sysctl_new.write('fs.suid_dumpable = 0\n') 

	sysctl_old.close() 
        sysctl_new.close() 

	replace_conf(sysctl_path, sysctl_path + '_tmp')

	return 0

def enable_core_dump():
	limits_path = rootPath + '/etc/security/limits.conf' 
        if True!=os.path.exists(limits_path):
                return 1

        limits_old = file(limits_path, 'r') 
        limits_new = file(limits_path+'_tmp', 'w') 
	pattern = re.compile(conf_pattern["core_dump_1"][1][0])

        for line in limits_old.readlines():
                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        limits_new.write(line+'\n') 
                        continue 

                if pattern.match(line):
                        continue 

                limits_new.write(line+'\n') 


        limits_old.close() 
        limits_new.close() 

	replace_conf(limits_path, limits_path + '_tmp')


        sysctl_path = rootPath + '/etc/sysctl.conf' 
        if True!=os.path.exists(sysctl_path):
                return 1

        sysctl_old = file(sysctl_path, 'r') 
        sysctl_new = file(sysctl_path+'_tmp', 'w') 

	pattern = re.compile(conf_pattern["core_dump_2"][1][0])
        for line in sysctl_old.readlines():
                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        sysctl_new.write(line+'\n') 
                        continue 

                if pattern.match(line):
                        continue 

                sysctl_new.write(line+'\n') 

	sysctl_old.close() 
        sysctl_new.close() 

	replace_conf(sysctl_path, sysctl_path + '_tmp')

	return 0



def disable_prelink():
	prelink_path = rootPath + '/etc/sysconfig/prelink' 
        if True!=os.path.exists(prelink_path):
                return 1

        prelink_old = file(prelink_path, 'r') 
        prelink_new = file(prelink_path+'_tmp', 'w') 

        for line in prelink_old.readlines():
                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        prelink_new.write(line+'\n') 
                        continue 

                if -1!=line.find('PRELINKING'): # find 'PRELINKING', just skip this line
                        continue 

                prelink_new.write(line+'\n') 

        prelink_new.write('PRELINKING=no') 

        prelink_old.close() 
        prelink_new.close() 

	replace_conf(prelink_path, prelink_path + '_tmp')
        return 0

def enable_prelink():
	prelink_path = rootPath + '/etc/sysconfig/prelink' 
        if True!=os.path.exists(prelink_path):
                return 1

        prelink_old = file(prelink_path, 'r') 
        prelink_new = file(prelink_path+'_tmp', 'w') 
	pattern = re.compile(conf_pattern["prelink"][1][0])

        for line in prelink_old.readlines():
                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        prelink_new.write(line+'\n') 
                        continue 

                if pattern.match(line):
                        continue 

                prelink_new.write(line+'\n') 


        prelink_old.close() 
        prelink_new.close() 

	replace_conf(prelink_path, prelink_path + '_tmp')
        return 0

def disable_ip_traffic():
	sysctl_path = rootPath + '/etc/sysctl.conf' 
        if True!=os.path.exists(sysctl_path):
                return 1

        sysctl_old = file(sysctl_path, 'r') 
        sysctl_new = file(sysctl_path+'_tmp', 'w') 

        for line in sysctl_old.readlines():
                line = line.strip() 

                if -1!=line.find('net.ipv4.conf.all.send_redirects'):
                        continue 

                if -1!=line.find('net.ipv4.conf.default.send_redirects'):
			continue 

		sysctl_new.write(line+'\n') 

	sysctl_new.write('net.ipv4.conf.all.send_redirects = 0\n') 
	sysctl_new.write('net.ipv4.conf.default.send_redirects = 0\n') 
	
        sysctl_new.close() 
        sysctl_old.close() 

	replace_conf(sysctl_path, sysctl_path + '_tmp')
        return 0


def enable_ip_traffic():
	sysctl_path = rootPath + '/etc/sysctl.conf' 
        if True!=os.path.exists(sysctl_path):
                return 1

        sysctl_old = file(sysctl_path, 'r') 
        sysctl_new = file(sysctl_path+'_tmp', 'w') 

	pattern_1 = re.compile(conf_pattern["ip_traffic"][1][0])
	pattern_2 = re.compile(conf_pattern["ip_traffic"][1][1])

        for line in sysctl_old.readlines():
                line = line.strip() 

                if pattern_1.match(line) or pattern_2.match(line):
			continue 

		sysctl_new.write(line+'\n') 

	
        sysctl_new.close() 
        sysctl_old.close() 

	replace_conf(sysctl_path, sysctl_path + '_tmp')
        return 0

def disable_wireless():
	version = os.uname()[2]

	proc = subprocess.Popen("chroot %s find /lib/modules/%s/kernel/drivers/net/wireless -name '*.ko' -type f"% (rootPath, version), stdout=subprocess.PIPE, shell=True)
	proc.wait()
	kos = proc.stdout.readlines()

	kl = []
	for line in kos:
		line = line.rstrip('\n')
		path = line.split('/')
		ko = path[len(path) - 1][:-3]
		kl.append(ko)


	blacklist_path = rootPath + '/etc/modprobe.d/blacklist.conf' 
        if True==os.path.exists(blacklist_path): # '/etc/modprobe.d/modprobe.conf' is exist
                old_conf = file(blacklist_path, 'r') 
                new_conf = file(blacklist_path+'_tmp', 'w') 
		for line in old_conf.readlines():
			line = line.strip()
			if not len(line) or line.startswith('#'):
				new_conf.write(line + '\n')
				continue
			if line.split()[1] in kl:
				continue
			new_conf.write(line + '\n')
		old_conf.close()

		# append our blacklist
		new_conf.write("\n")
		for ko in kl:
			new_conf.write("blacklist " + ko + '\n')
		new_conf.close()

		replace_conf(blacklist_path, blacklist_path + '_tmp')
	else:
		new_conf = file(blacklist_path, 'w')
		# append our blacklist
		new_conf.write("\n")
		for ko in kl:
			new_conf.write("blacklist " + ko + '\n')
		new_conf.close()

		repair_perm(blacklist_path)
	return 0



def enable_wireless():
	version = os.uname()[2]

	proc = subprocess.Popen("chroot %s find /lib/modules/%s/kernel/drivers/net/wireless -name '*.ko' -type f"% (rootPath, version), stdout=subprocess.PIPE, shell=True)
	proc.wait()
	kos = proc.stdout.readlines()

	kl = []
	for line in kos:
		line = line.rstrip('\n')
		path = line.split('/')
		ko = path[len(path) - 1][:-3]
		kl.append(ko)

	blacklist_path = rootPath + '/etc/modprobe.d/blacklist.conf' 
        if True==os.path.exists(blacklist_path): # '/etc/modprobe.d/modprobe.conf' is exist
                old_conf = file(blacklist_path, 'r') 
                new_conf = file(blacklist_path+'_tmp', 'w') 
		for line in old_conf.readlines():
			line = line.strip()
			if not len(line) or line.startswith('#'):
				new_conf.write(line + '\n')
				continue

			if line.split()[1] in kl:
				continue
			new_conf.write(line + '\n')
		old_conf.close()
		new_conf.close()
		replace_conf(blacklist_path, blacklist_path + '_tmp')
	return 0

		

def disable_ipv6():
	files_array = os.popen('ls %s/etc/sysconfig/network-scripts/ | grep ifcfg-'% rootPath).readlines() 
        for file_name in files_array:
                prefix = rootPath +'/etc/sysconfig/network-scripts/' 
                file_old = prefix + file_name.rstrip('\n') 
                file_new = prefix + file_name.rstrip('\n') + '_tmp' 

                f_old = file(file_old, 'r') 
                f_new = file(file_new, 'w') 

                for line in f_old.readlines():
                        line = line.strip() 

                        if not len(line) or line.startswith('#'):
                                f_new.write(line+'\n') 
                                continue 

                        if -1!=line.find('IPV6INIT'):
                                continue 

                        f_new.write(line+'\n') 

                f_new.write('IPV6INIT=no\n') 

                f_old.close() 
                f_new.close() 

		replace_conf(file_old, file_new)

	no_load_ipv6() 

        return 0

def enable_ipv6():
	files_array = os.popen('ls %s/etc/sysconfig/network-scripts/ | grep ifcfg-'% rootPath).readlines() 
        for file_name in files_array:
                prefix = rootPath +'/etc/sysconfig/network-scripts/' 
                file_old = prefix + file_name.rstrip('\n') 
                file_new = prefix + file_name.rstrip('\n') + '_tmp' 

                f_old = file(file_old, 'r') 
                f_new = file(file_new, 'w') 
		pattern = re.compile(conf_pattern["ipv6_ifcfg"][1][0])

                for line in f_old.readlines():
                        line = line.strip() 

                        if not len(line) or line.startswith('#'):
                                f_new.write(line+'\n') 
                                continue 

                        if pattern.match(line):
                                continue 

                        f_new.write(line+'\n') 

                f_old.close() 
                f_new.close() 

		replace_conf(file_old, file_new)

	load_ipv6() 

        return 0


def config_iptables():
	cmd = "chroot %s /etc/init.d/libvirtd start "% rootPath
	proc = subprocess.Popen(cmd, shell=True)
	proc.wait()

	cmd = "chroot %s /etc/init.d/libvirtd stop "% rootPath
	proc = subprocess.Popen(cmd, shell=True)
	proc.wait()

        old_iptables = rootPath + '/etc/sysconfig/iptables' 

	replace_conf(old_iptables, "/usr/share/isoft_svmc/data/iptables", "yes")

	old_nfs = rootPath + '/etc/sysconfig/nfs'
	replace_conf(old_nfs, "/usr/share/isoft_svmc/data/nfs", "yes")

        return 0


def turn_off_services():
        service_array = ['abrtd', 'atd', 'autofs', 'avahi-daemon', 'kdump', 'mdmonitor', 'netfs', 'postfix'] 

        for service in service_array:
               	args = ["--level", "345", service, "off"]
		iutil.execWithRedirect("chkconfig", args, stdout="/dev/null", stderr="/dev/null", root=rootPath)

        return 



def no_load_ipv6():
	modprobe_path = rootPath + '/etc/modprobe.d/modprobe.conf' 
        if True==os.path.exists(modprobe_path): # '/etc/modprobe.d/modprobe.conf' is exist
                old_conf = file(modprobe_path, 'r') 
                new_conf = file(modprobe_path+'_tmp', 'w') 

                for line in old_conf.readlines():
                        line = line.strip() 
                        if not len(line) or line.startswith('#'):
                                new_conf.write(line+'\n') 
                                continue 

                        if -1!=line.find('ipv6'):#if found old ipv6-config line, skip it
                                continue 

                        new_conf.write(line+'\n') 

		new_conf.write('install ipv6 /bin/true\n') 

                old_conf.close() 
		new_conf.close() 

		replace_conf(modprobe_path, modprobe_path + '_tmp')

                return 

        conf = file(modprobe_path, 'w')  # create new file '/etc/modprobe.d/modprobe.conf'
        conf.write('install ipv6 /bin/true\n') 
        conf.close() 
	repair_perm(modprobe_path)
        return 0

def load_ipv6():
	modprobe_path = rootPath + '/etc/modprobe.d/modprobe.conf' 
        if True==os.path.exists(modprobe_path): # '/etc/modprobe.d/modprobe.conf' is exist
                old_conf = file(modprobe_path, 'r') 
                new_conf = file(modprobe_path+'_tmp', 'w') 
		pattern = re.compile(conf_pattern["ipv6_mod"][1][0])

                for line in old_conf.readlines():
                        line = line.strip() 
                        if not len(line) or line.startswith('#'):
                                new_conf.write(line+'\n') 
                                continue 

                        if pattern.match(line):
                                continue 

                        new_conf.write(line+'\n') 


                old_conf.close() 
		new_conf.close() 

		replace_conf(modprobe_path, modprobe_path + '_tmp')
	return 0

def disable_uncommon_protocols():
	modprobe_path = rootPath + '/etc/modprobe.d/modprobe.conf' 
        if True==os.path.exists(modprobe_path): # '/etc/modprobe.d/modprobe.conf' is exist
                old_conf = file(modprobe_path, 'r') 
                new_conf = file(modprobe_path+'_tmp', 'w') 

                for line in old_conf.readlines():
                        line = line.strip() 
                        if not len(line) or line.startswith('#'):
                                new_conf.write(line+'\n') 
                                continue 

                        if -1!=line.find('dccp'): #if found the old dccp config-line,just skip it
                                continue 

			if -1!=line.find('sctp'):
				continue 

			if -1!=line.find('rds'):
				continue 

			if -1!=line.find('tipc'):
				continue 

                        new_conf.write(line+'\n') 

		
                new_conf.write('install dccp /bin/true\n') 
		new_conf.write('install sctp /bin/true\n') 
		new_conf.write('install rds /bin/true\n') 
		new_conf.write('install tipc /bin/true\n') 

                old_conf.close() 
		new_conf.close() 

		replace_conf(modprobe_path, modprobe_path + '_tmp')

                return 0

        conf = file(modprobe_path, 'w')  # create new file '/etc/modprobe.d/modprobe.conf'
        conf.write('install dccp /bin/true\n') 
	conf.write('install sctp /bin/true\n') 
	conf.write('install rds /bin/true\n') 
	conf.write('install tipc /bin/true\n') 
        conf.close() 
	repair_perm(modprobe_path)
        return 0 


def enable_uncommon_protocols():
	modprobe_path = rootPath + '/etc/modprobe.d/modprobe.conf' 
        if True==os.path.exists(modprobe_path): # '/etc/modprobe.d/modprobe.conf' is exist
                old_conf = file(modprobe_path, 'r') 
                new_conf = file(modprobe_path+'_tmp', 'w') 
		pattern_1 = re.compile(conf_pattern["uncommon_protocol"][1][0])
		pattern_2 = re.compile(conf_pattern["uncommon_protocol"][1][1])
		pattern_3 = re.compile(conf_pattern["uncommon_protocol"][1][2])
		pattern_4 = re.compile(conf_pattern["uncommon_protocol"][1][3])

                for line in old_conf.readlines():
                        line = line.strip() 
                        if not len(line) or line.startswith('#'):
                                new_conf.write(line+'\n') 
                                continue 

			if pattern_1.match(line) or pattern_2.match(line) or pattern_3.match(line) or pattern_4.match(line):
				continue 

                        new_conf.write(line+'\n') 


                old_conf.close() 
		new_conf.close() 

		
		replace_conf(modprobe_path, modprobe_path + '_tmp')


	return 0


def password_quality():
	system_auth = rootPath + '/etc/pam.d/system-auth-ac' 

        if True==os.path.exists(system_auth):
		old_auth = file(system_auth, 'r') 
		new_auth = file(system_auth+'_tmp', 'w') 

		for line in old_auth.readlines():
			line = line.strip() 
			if not len(line) or line.startswith('#'):
				new_auth.write(line+'\n') 
				continue 

			if -1!=line.find('password') and -1!=line.find('requisite') and -1!=line.find('pam_cracklib.so'):
				new_auth.write('password requisite pam_passwdqc.so min=disabled,8,8,8,8\n') 
				continue 

			new_auth.write(line+'\n') 

		old_auth.close() 
		new_auth.close() 

		replace_conf(system_auth, system_auth + '_tmp')
	return 0

def no_password_quality():
	system_auth = rootPath + '/etc/pam.d/system-auth-ac' 

        if True==os.path.exists(system_auth):
		old_auth = file(system_auth, 'r') 
		new_auth = file(system_auth+'_tmp', 'w') 

		pattern = re.compile(conf_pattern["password"][1][0])
		for line in old_auth.readlines():
			line = line.strip() 
			if not len(line) or line.startswith('#'):
				new_auth.write(line+'\n') 
				continue 

			if pattern.match(line):
				continue 

			new_auth.write(line+'\n') 

		old_auth.close() 
		new_auth.close() 

		replace_conf(system_auth, system_auth + '_tmp')
	return 0



def authentication_single_user():
	sulogin_conf = rootPath + '/etc/init/rcS-sulogin.conf' 

	if True == os.path.exists(sulogin_conf):
		old_conf = file(sulogin_conf, 'r') 
		new_conf = file(sulogin_conf+'_tmp', 'w') 

		lines = old_conf.readlines()
		for line in lines:
			line = line.strip() 
			if not len(line) or line.startswith('#'):
				new_conf.write(line+'\n') 
				continue 

			if -1!=line.find('''[ -z "$SINGLE" ] && SINGLE=/sbin/sushell'''):
				new_conf.write(line+'\n') 
				value = "exec /sbin/sulogin\n"
				if lines.count(value) == 0:
					new_conf.write('exec /sbin/sulogin\n') 
				continue 

			new_conf.write(line+'\n') 

		old_conf.close() 
		new_conf.close() 

		replace_conf(sulogin_conf, sulogin_conf + '_tmp')
	return 0


def no_authentication_single_user():
	sulogin_conf = rootPath + '/etc/init/rcS-sulogin.conf' 

	if True == os.path.exists(sulogin_conf):
		old_conf = file(sulogin_conf, 'r') 
		new_conf = file(sulogin_conf+'_tmp', 'w') 

		pattern = re.compile(conf_pattern["single_user"][1][0])
		for line in old_conf.readlines():
			line = line.strip() 
			if not len(line) or line.startswith('#'):
				new_conf.write(line+'\n') 
				continue 

			if pattern.match(line):
				continue 

			new_conf.write(line+'\n') 

		old_conf.close() 
		new_conf.close() 

		replace_conf(sulogin_conf, sulogin_conf + '_tmp')
	return 0


def login_time_out():
	tmout_path = rootPath + '/etc/profile.d/tmout.sh' 

	tmout = file(tmout_path, 'w') 

	tmout.write('TMOUT=900\n') 
	tmout.write('readonly TMOUT\n') 
	tmout.write('export TMOUT\n') 

	tmout.close() 
	return 0

def no_login_time_out():
	tmout_path = rootPath + '/etc/profile.d/tmout.sh' 
	if os.path.exists(tmout_path) == True:
		os.popen("rm -f %s"% tmout_path)
	return 0

def disable_graphic_for_root():
	gdm_password_conf = rootPath + '/etc/pam.d/gdm-password' 

	if True == os.path.exists(gdm_password_conf):
		old_conf = file(gdm_password_conf, 'r') 
		new_conf = file(gdm_password_conf+'_tmp', 'w') 

		first = True
		lines = old_conf.readlines()
		for line in lines:
			line = line.strip() 
			if not len(line) or line.startswith('#'):
				new_conf.write(line+'\n') 
				continue 

			if first == True and "auth" in line :
				first = False
				value = 'auth required pam_succeed_if.so user != root quiet\n'
				if lines.count(value) == 0:
					new_conf.write(value) 
				new_conf.write(line + '\n')
				continue 

			new_conf.write(line+'\n') 

		old_conf.close() 
		new_conf.close() 

		replace_conf(gdm_password_conf, gdm_password_conf + '_tmp')
		return 0
	return 1


def enable_graphic_for_root():
	gdm_password_conf = rootPath + '/etc/pam.d/gdm-password' 

	if True == os.path.exists(gdm_password_conf):
		old_conf = file(gdm_password_conf, 'r') 
		new_conf = file(gdm_password_conf+'_tmp', 'w') 

		pattern = re.compile(conf_pattern["root_graphical"][1][0])
		for line in old_conf.readlines():
			line = line.strip() 
			if not len(line) or line.startswith('#'):
				new_conf.write(line+'\n') 
				continue 

			if pattern.match(line):
				continue 

			new_conf.write(line+'\n') 

		old_conf.close() 
		new_conf.close() 

		replace_conf(gdm_password_conf, gdm_password_conf + '_tmp')
		return 0
	return 1

	
def enable_module_signature():
	grub_path = rootPath + '/boot/grub/grub.conf' 
        if True!=os.path.exists(grub_path):
                return 1

        old_grub = file(grub_path, 'r') 
        new_grub = file(grub_path+'_tmp', 'w') 

        for line in old_grub.readlines():

                line = line.strip() 
                if not len(line) or line.startswith('#'):
                        new_grub.write(line+'\n') 
                        continue 

                if -1!=line.find('kernel') and -1!=line.find('vmlinuz'):
                        if -1==line.find('enforcemodulesig'): 
				new_grub.write(line+' enforcemodulesig=1\n') 
				continue
			if -1 != line.find('enforcemodulesig=0'): 
				line = line.replace('enforcemodulesig=0','enforcemodulesig=1')
				new_grub.write(line + '\n') 
                                continue 

                new_grub.write(line+'\n') 

        old_grub.close() 
        new_grub.close() 

	replace_conf(grub_path, grub_path + '_tmp')

        return 0
	
def disable_module_signature():
	grub_path = rootPath + '/boot/grub/grub.conf' 
        if True!=os.path.exists(grub_path):
                return 1

        old_grub = file(grub_path, 'r') 
        new_grub = file(grub_path+'_tmp', 'w') 

        for line in old_grub.readlines():

                line = line.strip() 
                
                if -1!=line.find('kernel') and -1!=line.find('vmlinuz'):
                        if -1 != line.find('enforcemodulesig'): 
				line = re.sub('enforcemodulesig=1', '', line)

                new_grub.write(line+'\n') 

        old_grub.close() 
        new_grub.close() 

	replace_conf(grub_path, grub_path + '_tmp')

        return  0


def fail_lockout():
	system_auth = rootPath + '/etc/pam.d/system-auth-ac' 

	tag001 = 0 
	tag002 = 0 
	
	if os.path.exists(system_auth) == True:
		old_auth = file(system_auth, 'r') 
		new_auth = file(system_auth+'_tmp', 'w') 

		lines = old_auth.readlines()
		for line in lines:
			line = line.strip() 
			if not len(line) or line.startswith('#'):
				new_auth.write(line+'\n') 
				continue 

			if -1!=line.find('auth') and 0==tag001:
				value = "auth required pam_tally2.so deny=5 onerr=fail unlock_time=900\n"
				if lines.count(value) == 0:
					new_auth.write('auth required pam_tally2.so deny=5 onerr=fail unlock_time=900\n') 
				new_auth.write(line+'\n') 
				tag001 = 1 
				continue 

			if -1!=line.find('account') and 0==tag002:
				value = "account required pam_tally2.so\n"
				if lines.count(value) == 0:
					new_auth.write('account required pam_tally2.so\n') 
				new_auth.write(line+'\n') 
				tag002 = 1 
				continue 

			new_auth.write(line+'\n') 

		old_auth.close() 
		new_auth.close() 

		replace_conf(system_auth, system_auth + '_tmp')
	else:# write in new file
		conf = file(system_auth, 'w')
		conf.write("auth required pam_tally2.so deny=5 onerr=fail unlock_time=900\n")
		conf.write('account required pam_tally2.so\n') 
		conf.close()

	return 0

def no_fail_lockout():
	system_auth = rootPath + '/etc/pam.d/system-auth-ac' 

	tag001 = 0 
	tag002 = 0 

	if os.path.exists(system_auth) == True:

		old_auth = file(system_auth, 'r') 
		new_auth = file(system_auth+'_tmp', 'w') 

		pattern_1 = re.compile(conf_pattern["fail_lock"][1][0])
		pattern_2 = re.compile(conf_pattern["fail_lock"][1][1])
		for line in old_auth.readlines():
			line = line.strip() 
			if (pattern_1.match(line) and tag001 == 0) or (pattern_2.match(line) and tag002 == 0):
				continue 

			new_auth.write(line+'\n') 

		old_auth.close() 
		new_auth.close() 

		replace_conf(system_auth, system_auth + '_tmp')

	return 0

def get_cur_services():
	services_store = []
	services = ("abrtd", "cups", "drbd", "heartbeat", "atd", "autofs", "avahi-daemon", "iscsi", "iscsid", "kdump", "mdmonitor", "netfs", "postfix")
	services_option =("iscsi", "iscsid")
	proc = subprocess.Popen("chroot %s bash -c \"LANG=C chkconfig --list\""% rootPath, stdout=subprocess.PIPE, shell=True)
	proc.wait()
	serv = proc.stdout.readlines()
	for x in serv:
		x = x[:-1]
		x = x.lstrip()
		if x.startswith("xinetd"):
			break
		if x.startswith(services):
			sl = x.split()
			service = []
			service.append(sl[0]) # name

			if "on" in sl[4] or "on" in sl[5]: # state
				service.append(_("on"))
			else:
				service.append(_("off"))
			service.append(_("off")) # recommend
			if sl[0] in services_option:
			    service.append(False)	# default choice
			else:
			    service.append(True)	# default choice
			services_store.append(service)
	
	#print services_store
	return services_store


def default():

	mount_for_noroot() 
	mount_for_tmp() 
	mount_for_shm() 

	disable_usb_storage() 
	#disable_usb_device() 
	daemon_umask() 
	disable_core_dump() 
	disable_prelink() 
	disable_ip_traffic() 
	disable_wireless() 
	disable_ipv6() 
	disable_uncommon_protocols() 
	password_quality() 
	authentication_single_user() 
	login_time_out() 
	fail_lockout() 

	add_nodev_for_fstab() 
	config_iptables() 
	turn_off_services() 

	return 0

# is configured before
def is_active(conf, regs):

	path = rootPath + conf

	if os.path.exists(path) == False:
		return False
	f = file(path, "r")
	lines = f.readlines()
	f.close()

	for reg in regs:
		ret = False
		pattern = re.compile(reg)
		for line in lines:
			match = pattern.match(line)
			if match:
				ret = True
				break
		if ret == False:
			return False

	return True


def doAide():
    # relabel files
    #cmd = "setfiles -q -l -F -r %s -p /etc/selinux/targeted/contexts/files/file_contexts / "% rootPath
    #proc = subprocess.Popen(cmd, shell=True)
    #proc.wait()

    try:
	if not os.path.exists("%s/boot/.aide"% rootPath):
	    os.mkdir("%s/boot/.aide"% rootPath, 600)

	proc = subprocess.Popen("/usr/sbin/aide --init &>/dev/null", shell=True)
	proc.wait()

	proc = subprocess.Popen("mv %s/boot/.aide/aide.db.new %s/boot/.aide/aide.db"%(rootPath, rootPath), shell=True)
	proc.wait()

	proc = subprocess.Popen("/bin/cp %s/.i-soft/isoft.pub  %s/boot/"% (livePath, rootPath), shell=True)
	proc.wait()
	proc = subprocess.Popen("/bin/cp %s/.i-soft/pub.gpg  %s/boot/.aide/"% (livePath, rootPath), shell=True)
	proc.wait()
	proc = subprocess.Popen("/usr/bin/gpg --import %s/.i-soft/pub.gpg &>/dev/null"% livePath, shell=True)
	proc.wait()
	proc = subprocess.Popen("/usr/bin/gpg --import %s/.i-soft/sec.gpg &>/dev/null"% livePath, shell=True)
	proc.wait()

	if  os.path.exists("%s/boot/.aide/aide.db.sig"%rootPath):
	    os.popen("rm -f %s/boot/.aide/aide.db.sig"%rootPath)

	proc = subprocess.Popen("/usr/bin/gpg -o %s/boot/.aide/aide.db.sig -s %s/boot/.aide/aide.db &>/dev/null"% (rootPath, rootPath), shell=True)
	proc.wait()

	# add cron task
	proc = subprocess.Popen("cp /usr/share/isoft_svmc/data/gpg-check.sh %s/usr/sbin/"% rootPath, shell=True)
	proc.wait()
	proc = subprocess.Popen("grep -q 'gpg-check.sh' %s/etc/crontab"% rootPath, shell=True)
        proc.wait()

        if proc.returncode != 0:    
	    proc = subprocess.Popen("/usr/sbin/chroot %s sed -i '16a \
	    1  0  *  *  * root /usr/sbin/gpg-check.sh' /etc/crontab"% rootPath, shell=True)
	    proc.wait()

	# host part
	proc = subprocess.Popen("/usr/sbin/chroot %s /usr/sbin/aide --init &>/dev/null" % rootPath, shell=True)
	proc.wait()

	proc = subprocess.Popen("/usr/sbin/chroot %s mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db &>/dev/null" % rootPath, shell=True)
	proc.wait()

	# sign it
	if  os.path.exists("%s/var/lib/aide/aide.db.sig"%rootPath):
	    os.popen("rm -f %s/var/lib/aide/aide.db.sig"%rootPath)
	proc = subprocess.Popen("/usr/bin/gpg -o %s/var/lib/aide/aide.db.sig -s %s/var/lib/aide/aide.db &>/dev/null"% (rootPath, rootPath), shell=True)
	proc.wait()

	# import keys
	proc = subprocess.Popen("/usr/sbin/chroot %s gpg --import /boot/.aide/pub.gpg  &>/dev/null"% rootPath, shell=True)
	proc.wait()

	# relable
	proc = subprocess.Popen("touch %s/.autorelabel"% rootPath, shell=True)
	proc.wait()

    except OSError:
	print "aide initialize error!"

def find_prefix(line):
    line = line.strip()
    opts = line.split()
    pos = opts[1].find("vmlinuz")
    return opts[1][:pos - 1]


def add_key_to_grub():
    #get public key base64 format
    cmd = "gpg --homedir . --export --keyring /mnt/live/.i-soft/isoft.pub i-soft | base64 | tr -d '\n'"
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    proc.wait()

    key=proc.stdout.readlines()

    # create a file to hold the key
    key_file = file(rootPath + "/boot/pkey", 'w')
    key_file.write(key[0])
    key_file.close()

    # add key entry to grub.conf
    grub_conf_path = rootPath + "/boot/grub/grub.conf"

    if os.path.exists(grub_conf_path) != True:
        return 1

    old_conf = file(grub_conf_path, 'r') 
    new_conf = file(grub_conf_path +'_tmp', 'w') 
    
    stop = False
    first = True
    for line in old_conf.readlines():
	find = line.strip() 
	if not len(find) or find.startswith('#'):
	    new_conf.write(line)
	    continue 

	if -1 != find.find('kernel') and first == True:
	    first = False
	    prefix = find_prefix(find)
	    if "pubkey=" in find:
		line = '\t'
		for opt in find.split():
		    if opt.startswith("pubkey="):
			opt = "pubkey=%s/pkey"%prefix
		    line = line + opt + ' '
		new_conf.write(line + '\n')
	    else:
		line = line.rstrip('\n')
		line = line + " pubkey=%s/pkey"%prefix + '\n'
		new_conf.write(line)
	    continue
	# one entry iSec 1 only!
	if "title" in find:
            if stop == False:
                stop = True
	    else:
                break
	new_conf.write(line)

    old_conf.close()
    new_conf.close()

    replace_conf(grub_conf_path, grub_conf_path + '_tmp')

def fix_grub_title():
    f = file("%s/etc/system-release"%rootPath)
    rel_str = f.readline().split()
    f.close()
    release = rel_str[0] + ' ' + rel_str[2]
    grub_path = "%s/boot/grub/grub.conf"% rootPath
    if os.path.exists(grub_path) != True:
        return 1
    cmd = "sed -i '/^title/s/CentOS Linux/%s/' %s"% (release, grub_path)
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()

def avoid_grubby_error():

    # first get root entry from /proc/mounts
    local_mtab = "/proc/mounts"
    conf = file(local_mtab, 'r')
    lines = conf.readlines()
    conf.close()
    for line in lines:
	line = line.strip()
	items = line.split()
	if len(items) > 0 and not line.startswith('#') and items[1] == rootPath:
	    root_line = line
	    break;
    
    # the write root entry int /etc/mtab
    mtab_path = rootPath + "/etc/mtab"
    old_conf = file(mtab_path, 'r') 
    lines = old_conf.readlines()
    old_conf.close()

    new_conf = file(mtab_path + "_tmp", 'w')
    for line in lines:
	line = line.strip()
	items =line.split()
	if len(items) > 1 and not line.startswith('#') and items[1] == '/':
	    opts = root_line.split()
	    opts[1] = '/'
	    for opt in opts:
		new_conf.write(opt + ' ')
	    new_conf.write('\n')
	    continue
	new_conf.write(line + '\n')
    new_conf.close()

    replace_conf(mtab_path, mtab_path + '_tmp')


def resign_kernel_modules():
    # walkaround grubby complain
    avoid_grubby_error()
    
    # remove the old kernel 
    cmd = "rpm -e kernel-2.6.32-220.el6.x86_64 --root %s --nodeps &>/dev/null"% rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()

    # install the kernel , force :-)	
    cmd = "rpm -i %s/.RPM/kernel-2.6.32-220.el6.isoft.x86_64.rpm --root %s --force --nodeps "% (livePath, rootPath)
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()

    # first get kernel release name
    kernel = "2.6.32-220.el6.isoft.x86_64"
    # then sign the kernel modules
    iutil.execWithRedirect("/usr/sbin/resign-modules", ["--kernel", kernel, "--root", rootPath], stdout="/dev/tty5", stderr="/dev/tty5")

    # rebuild initrdramfs.img
    args = ["--package", "%s"%kernel, "--mkinitrd", "--dracut", "--depmod", "--update", "%s"% kernel]
    iutil.execWithRedirect("/sbin/new-kernel-pkg", args, stdout="/dev/tty5", stderr="/dev/tty5", root=rootPath)
    args = ["--add-kernel", "%s"%kernel]
    iutil.execWithRedirect("/sbin/weak-modules", args, stdout="/dev/tty5", stderr="/dev/tty5", root=rootPath)

    # update grub.conf
    add_key_to_grub()
    fix_grub_title()
    
def apply_audit_and_policy():
    # rpms to remove
    old_rpms = [ "selinux-policy-3.7.19-54.el6.noarch", "selinux-policy-targeted-3.7.19-54.el6.noarch"]
    for rpm in old_rpms:
	cmd = "rpm -e %s --root %s --nodeps &>/dev/null"% (rpm, rootPath)
	proc = subprocess.Popen(cmd, shell=True)
	proc.wait()

    # do some clean 
    cmd = "rm -rf %s/etc/selinux/targeted"%rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()    
    
    cmd = "rm -f %s/etc/selinux/config"%rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()    

    # rpms to install
    rpms = ["selinux-policy-3.7.19-55.el6.isoft.noarch.rpm", "selinux-policy-targeted-3.7.19-55.el6.isoft.noarch.rpm"]

    # install packages, --force and --nodeps :-)	
    for rpm in rpms:
	cmd = "rpm -i  %s/.RPM/%s --root %s --force --nodeps "% (livePath, rpm, rootPath)
	proc = subprocess.Popen(cmd, shell=True)
	proc.wait()

    # replace audit.rules
    cmd = "cp /usr/share/isoft_svmc/data/audit.rules %s/etc/audit/audit.rules.1 && mv %s/etc/audit/audit.rules.1 %s/etc/audit/audit.rules "% (rootPath, rootPath, rootPath)
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()

    # load policy 
    replace_conf("%s/usr/share/dracut/modules.d/99base/selinux-loadpolicy.sh"%rootPath, "/usr/share/isoft_svmc/data/selinux-loadpolicy.sh", "yes");
    

def config_ssh():
    conf_path = rootPath + "/etc/ssh/ssh_config"
    present = False
    if os.path.exists(conf_path):
	old_conf = file(conf_path, 'r')
	new_conf = file(conf_path + "_tmp", 'w')
	for line in old_conf.readlines():
	    if "StrictHostKeyChecking" in line:
                present = True
		new_conf.write("StrictHostKeyChecking no\n")
	        continue
	    new_conf.write(line)
	if present == False:
            new_conf.write("StrictHostKeyChecking no\n")
	old_conf.close()
	new_conf.close()
        replace_conf(conf_path, conf_path + "_tmp")
    else:
        conf = file(conf_path, 'w')
        conf.write("StrictHostKeyChecking no\n")
        conf.close()
        repair_perm(conf_path)

def config_sudoers():
    conf_path = rootPath + "/etc/sudoers"
    present = False
    if os.path.exists(conf_path):
	old_conf = file(conf_path, 'r')
	new_conf = file(conf_path + "_tmp", 'w')
	for line in old_conf.readlines():
	    if "Defaults" in line and "requiretty" in line:
		new_conf.write("# Defaults\trequiretty\n")
	        continue
	    if "%wheel" in line and "NOPASSWD" in line:
                present = True
		new_conf.write("%wheel\tALL=(ALL)\tNOPASSWD: ALL\n")
		continue
	    new_conf.write(line)
	if present == False:
	    new_conf.write("%wheel\tALL=(ALL)\tNOPASSWD: ALL\n")
	old_conf.close()
	new_conf.close()
        replace_conf(conf_path, conf_path + "_tmp")
    else:
        conf = file(conf_path, 'w')
        conf.write("%wheel\tALL=(ALL)\tNOPASSWD: ALL\n")
        conf.close()
        repair_perm(conf_path)



def create_sysadmin():
    cmd = "chroot %s adduser sysadmin"% rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()

def config_sysadmin():
    cmd = "chroot %s usermod -G wheel sysadmin"% rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()
    
    config_ssh()
    config_sudoers()

def config_selinux_driver():
    cmd = r"grep -q '^[^#]\s*security_driver\s*=\s*\"selinux\"' %s/etc/libvirt/qemu.conf"%rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()
    if proc.returncode != 0:
	cmd = r"sed -i 's/^.*\(security_driver\s*=\s*\).*$/\1\"selinux\"/' %s/etc/libvirt/qemu.conf"%rootPath
	proc = subprocess.Popen(cmd, shell=True)
	proc.wait()
	

def disable_interactive_startup():
    cmd = "sed -i 's/^\s*PROMPT=yes/PROMPT=no/' %s/etc/sysconfig/init"%rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()

def enable_interactive_startup():
    cmd = "sed -i 's/^\s*PROMPT=no/PROMPT=yes/' %s/etc/sysconfig/init"%rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()

def shm_noexec():
    cmd = "grep -q 'remount shm for noexec' %s/etc/rc.d/rc.sysinit"%rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()
    if proc.returncode !=0:
    	cmd = "sed -i '625a\\\n\
\\\n\
# remount shm for noexec\\\n\
mount -o remount /dev/shm\\\n' %s/etc/rc.d/rc.sysinit"%rootPath
	proc = subprocess.Popen(cmd, shell=True)
	proc.wait()

def tmp_noexec():
    cmd = "grep -q 'remount tmp for noexec' %s/etc/rc.d/rc.sysinit"%rootPath
    proc = subprocess.Popen(cmd, shell=True)
    proc.wait()
    if proc.returncode != 0:
	cmd = "sed -i '507a\\\n\
\\\n\
# remount tmp for nodev, nosuid\\\n\
mount -o bind,nodev,nosuid /tmp /tmp\\\n\
mount -o remount /tmp' %s/etc/rc.d/rc.sysinit"%rootPath
    	proc = subprocess.Popen(cmd, shell=True)
    	proc.wait()
       

def boot_aide():
        bash = '''
wait_reboot(){
    if [ -x  /usr/bin/plymouth ];then
        /usr/bin/plymouth hide-splash
    fi
    echo "Press 'Enter' to restart the system, You should use i-VirtualCloud Live CD to rescue the system!"
    while read x ; do
        if [ "X$x" == "X" ]; then
            /sbin/reboot -f
        fi
    done
}

aide_check(){
    cat > /var/aide_echo.sh << EOF
#!/bin/bash
# echo something while aide is in process
    while [ 1 -eq 1 ]
    do
	if [ -f /tmp/aide_done ]; then
	    echo 
	    echo " Done!"
	    rm -f /tmp/aide_done &>/dev/null
	    exit 0
	fi
	echo -n "#"
	sleep 1
    done
EOF

    chmod +x /var/aide_echo.sh

    if [ ! -e /var/lib/aide/aide.db ] ; then
        echo "**** Error: AIDE database not found."
	echo "**** Run 'aide --init' and move the appropriate database file."
	return 1
    elif [ -f /etc/aide.conf ]; then
        if [ -f /var/lib/aide/aide.db.sig ]; then
      	    pushd /var/lib/aide >/dev/null
            echo "Verifying the GPG signature on the database..."
	    echo ""
	    gpg --import /boot/isoft.pub
	    gpg --verify aide.db.sig
	    echo ""
            if [ "$?" == "1" ]; then
                echo "************************************************************"
                echo "GPG signature FAILED!  Your database has been tampered with!"
                echo "************************************************************"
		return 1
            fi
	    popd >/dev/null
	else
	    return 1
	fi
        # run check
        if [ -x /usr/sbin/aide ]; then
            echo "********************************************************************************"
            echo "************ Notice -- checking the integrity of important files. **************"
            echo "********** Checking could take a very long time, Please wait... ****************"
            echo "********************************************************************************"

	    /var/aide_echo.sh &
            /usr/sbin/aide --check &> /tmp/aide.log

	    rc=$?
	    touch /tmp/aide_done
	    sleep 2

            if [ $rc -ne 0 ]; then
		sed -n -e '/added: /p' -e '/changed: /p' -e '/removed: /p' /tmp/aide.log  > /tmp/aide.files

		echo -en "\e[1;31m"
		echo "Files do NOT match the database:"
		echo ""
		cat /tmp/aide.files
		echo -en "\e[0m"
		
		ko_nr=$(grep -c ": /lib/modules/$(/bin/uname -r)/.*\.ko" /tmp/aide.files)
		if [ "$ko_nr" -ne $(wc -l /tmp/aide.files | awk '{print $1}') ]; then
			echo "********************************************************************************"
			echo 
			echo "Warning !!! Maybe an indication of an attack against your system," 
			echo "or Maybe the result of something innocuous such as configuration change or a software update."
			echo 
			echo "********************************************************************************"

			return 1
		fi

		echo "********************************************************************************"
		echo 
		echo "Warning !!!  Kernel modules list above do not match the database."
		echo "But system will continue to boot, maybe you should take a look at"
		echo "what happened by use the i-VirtualCloud Live CD."
		echo "Press any key to continue..."
		echo 
		echo "********************************************************************************"
		read X

		return 0
            fi

	else 
	    return 1
        fi
    else
	return 1
    fi
    return 0
}

if [ -e /etc/sysconfig/isoft_svmc ];then
    aide_check
    if [ $? -ne 0 ]; then
	wait_reboot
    fi
    rm -f /var/aide_echo.sh &>/dev/null
fi
        '''
        # /etc/rc.d/rc.sysinit
	cmd = "grep -q 'aide_check' %s/etc/rc.d/rc.sysinit"% rootPath
	proc = subprocess.Popen(cmd, shell=True)
	proc.wait()
	if proc.returncode != 0:
	    sysinit_path = "%s/etc/rc.d/rc.sysinit" %rootPath
	    sysinit_old = file(sysinit_path, 'r')
	    sysinit_new = file(sysinit_path + "_tmp", 'w')
	    
	    lines = sysinit_old.readlines()
	    sysinit_old.close()
	    linenum = 0
	    while linenum < len(lines):
		if linenum == 507:
		    sysinit_new.write(bash + '\n')
		    linenum = linenum + 1
		    continue
		sysinit_new.write(lines[linenum])
		linenum = linenum + 1

	    sysinit_new.close()
	    cmd = "sed -i 's/Fedora/i-VirtualCloud/g' %s"%(sysinit_path + '_tmp')
	    proc = subprocess.Popen(cmd, shell=True)
	    proc.wait()
	    replace_conf(sysinit_path, sysinit_path + "_tmp")
